#!/usr/bin/env python3
"""
开机自启管理模块
用于管理Windows开机自启功能
"""

import winreg
import os
import sys
import traceback

class AutoStartManager:
    """Windows开机自启管理器"""
    
    def __init__(self):
        """初始化自启管理器"""
        self.app_name = "ResourceMonitor"
        self.registry_key = r"Software\Microsoft\Windows\CurrentVersion\Run"
        
    def get_executable_path(self):
        """获取当前可执行文件的完整路径
        
        Returns:
            str: 可执行文件路径
        """
        if getattr(sys, 'frozen', False):
            # 如果是PyInstaller打包的exe文件
            return sys.executable
        else:
            # 如果是Python脚本，返回Python解释器和脚本路径
            script_path = os.path.abspath(__file__).replace('auto_start.py', 'app.py')
            return f'"{sys.executable}" "{script_path}"'
    
    def is_auto_start_enabled(self):
        """检查是否已启用开机自启
        
        Returns:
            bool: True如果已启用，False如果未启用
        """
        try:
            with winreg.OpenKey(winreg.HKEY_CURRENT_USER, self.registry_key, 0, winreg.KEY_READ) as key:
                try:
                    value, _ = winreg.QueryValueEx(key, self.app_name)
                    # 检查注册表中的路径是否与当前程序路径匹配
                    current_path = self.get_executable_path()
                    return value.strip('"') == current_path.strip('"')
                except FileNotFoundError:
                    return False
        except Exception as e:
            print(f"检查开机自启状态时出错: {e}")
            return False
    
    def enable_auto_start(self):
        """启用开机自启
        
        Returns:
            bool: True如果成功，False如果失败
        """
        try:
            exe_path = self.get_executable_path()
            
            # 打开注册表键
            with winreg.OpenKey(winreg.HKEY_CURRENT_USER, self.registry_key, 0, 
                              winreg.KEY_SET_VALUE) as key:
                # 设置注册表值
                winreg.SetValueEx(key, self.app_name, 0, winreg.REG_SZ, exe_path)
            
            print(f"已启用开机自启: {exe_path}")
            return True
            
        except Exception as e:
            print(f"启用开机自启时出错: {e}")
            traceback.print_exc()
            return False
    
    def disable_auto_start(self):
        """禁用开机自启
        
        Returns:
            bool: True如果成功，False如果失败
        """
        try:
            with winreg.OpenKey(winreg.HKEY_CURRENT_USER, self.registry_key, 0, 
                              winreg.KEY_SET_VALUE) as key:
                try:
                    winreg.DeleteValue(key, self.app_name)
                    print("已禁用开机自启")
                    return True
                except FileNotFoundError:
                    # 如果注册表项不存在，认为已经是禁用状态
                    print("开机自启已经是禁用状态")
                    return True
                    
        except Exception as e:
            print(f"禁用开机自启时出错: {e}")
            traceback.print_exc()
            return False
    
    def toggle_auto_start(self):
        """切换开机自启状态
        
        Returns:
            tuple: (成功标志, 新状态) 
                  成功标志: bool, True如果操作成功
                  新状态: bool, True如果现在是启用状态
        """
        current_status = self.is_auto_start_enabled()
        
        if current_status:
            success = self.disable_auto_start()
            new_status = False if success else current_status
        else:
            success = self.enable_auto_start()
            new_status = True if success else current_status
            
        return success, new_status
    
    def get_startup_command(self):
        """获取当前的启动命令
        
        Returns:
            str: 启动命令，如果未设置则返回None
        """
        try:
            with winreg.OpenKey(winreg.HKEY_CURRENT_USER, self.registry_key, 0, winreg.KEY_READ) as key:
                try:
                    value, _ = winreg.QueryValueEx(key, self.app_name)
                    return value
                except FileNotFoundError:
                    return None
        except Exception as e:
            print(f"获取启动命令时出错: {e}")
            return None

# 简单测试代码
if __name__ == "__main__":
    print("=== 开机自启管理器测试 ===")
    
    manager = AutoStartManager()
    
    print(f"当前可执行文件路径: {manager.get_executable_path()}")
    print(f"当前开机自启状态: {manager.is_auto_start_enabled()}")
    
    current_command = manager.get_startup_command()
    if current_command:
        print(f"当前启动命令: {current_command}")
    else:
        print("未设置启动命令")
    
    print("=== 测试完成 ===") 